# -*- coding: iso-8859-1 -*-
#
#	El manager v.0.01 - Derivart (http://www.derivart.info)
#	@Coded: Mar Cane / Martin Nadal (2009)
#
#from fileScanner import fileScanner
from random import randrange
from time import sleep
from threadPool import threadPool  
from webcrawlerSGAEChecker import webcrawlerSGAEChecker
from genPuid import genPuid
from song import song
from readAndWriteID3 import readAndWriteID3

class threadManager():

    def __init__(self,filescanner):
        self.filescanner = filescanner
        self.mySGAEChecker = webcrawlerSGAEChecker()
        self.readerID3 = readAndWriteID3()
        self.myGenPuid = genPuid()
        self.totalPoolTasks = 3
        self.currentTasksSGAE = 0
        self.totalFiles = 0
        self.currentTasksGenPuid = 0
        self.totalSGAETasksDone = 0
        self.totalPUIDTasksDone = 0
        self.totalPUIDTasks = 0
        self.queueAnalysedSongs = []
        self.poolSGAE=None

    def startPool(self):
        print "hello start"
        self.poolSGAE = threadPool(10)
        #self.poolGenPuid = ThreadPool(self.totalPoolTasks)
        print "hello end"

    #def setUpdateMethod(self, method ):
    #    self.updateMethod = method
    #  FINAL QUEUE *************************************************************************************
    def addToAnalysedQueque(self, newSong):
        self.queueAnalysedSongs.append(newSong)

    #  SGAE pull ***************************************************************************************

    def chechSongTask(self, nextSong):
        print "SGAE-Task open web ",nextSong.title, nextSong.singer
        isInSGAEThisSong = self.mySGAEChecker.chechSong(nextSong.title, nextSong.singer)
        sleep(2)
        nextSong.isSgae = isInSGAEThisSong
        return nextSong

    def taskSGAECallback(self, nextSong):
        self.addToAnalysedQueque(nextSong)
        self.totalSGAETasksDone +=1
        print " : SGAE-Task done : "+str(self.totalSGAETasksDone)
        print str(len(self.queueAnalysedSongs))+"/"+str(len(self.filescanner.getFiles()))
        print "==Callback called for SGAE"

    def startSGAEProcess(self, newSong):
        # Insert tasks into the queue and let them run
        #print newSong.singer
        self.poolSGAE.queueTask(self.chechSongTask, newSong, self.taskSGAECallback)

    # When all tasks are finished, allow the threads to terminate
	#MARTIN:añado 2 parametros para poder cancelar a lo bestia si pasamos False, False
    def endSGAEFinishProcess(self, waitForTasks = True, waitForThreads = True):
        self.poolSGAE.joinAll(waitForTasks,waitForThreads)

    #  GenPuid pull ***********************************************************************************

    def taskPuidCallback(self, nextSong):
        print "==Callback called for Puid"

    def startPuidProcess(self, newSong):
        # Insert tasks into the queue and let them run
        print newSong.singer
        self.poolGenPuid.queueTask(self.genPuidTask, newSong, self.taskPuidCallback)

    def genPuidTask(self, path):
        print path
        song = self.myGenPuid.checkPuid(path)
        if(song.singer !="" and song.title !="" ):
            self.startSGAEProcess(song)
        else:
            song.isError = True
            self.addToAnalysedQueque(song)

    # When all tasks are finished, allow the threads to terminate
    def endGenPuidFinishProcess(self):
        self.poolGenPuid.joinAll()

    #  ***********************************************************************************************

    def getAllSongsAnalysed(self):
        return self.queueAnalysedSongs

    def getTotalSongsAnalysed(self):
        return len(self.queueAnalysedSongs)

    def addAllFiles(self):
       print "hello threadmanager"
       #print self.filescanner.getTotal()
       #print "total files"+self.totalFiles
       for files in self.filescanner.getFiles():
            #print str(num)+" / "+str(self.filescanner.getTotal())+"-"+files
            metadata = self.readerID3.loadMetadata(files)
            #print "metadata:"+metadata['title'] +" "+metadata['artist']
            if(metadata['title']!='No Title' and metadata['title']!=' ' and metadata['title']!='' and  metadata['artist']!='No Artist' and  metadata['artist']!=' ' and  metadata['artist']!=''):
                print "add with metadatos ==>"+  files
                newsong = song(files,metadata['title'],metadata['artist'])
                self.startSGAEProcess(newsong)
            else:
                self.totalPUIDTasks +=1
                #self.genPuidTask(files)
                newsong = song(files,"No Title","No Artist")
                newsong.isError = True
                self.addToAnalysedQueque(newsong)
            #    print str(self.totalPUIDTasks)+"****** Don't have metadatos"
            
       #MARTIN:he comentado esta linea para que no se quede pillado, join hace que esperes a los hilos         
       #self.endSGAEFinishProcess()
       
    def isFinish(self):
	   #MARTIN: comparaba fichero y numero, nunca devolvía True
	   #añado que compruebe que no hay hilos
       return  len(self.queueAnalysedSongs)==self.filescanner.getTotal()

